<template>
    <p>
        <a-button type="primary" @click="add">新建</a-button>

    </p>


    <a-table :data-source="contentsList"
             :columns="columns"
             :pagination="pagination"
             :loading="loading"
             @change="handleTableChange">
        <template #pic="{text,record,index}">
            <a-image :src="text" :width="100" :height="50"/>
        </template>
        <template #status="{text,record,index}">
            {{text==1?'有效':'无效'}}
        </template>
        <template v-slot:action="{text,record}">
            <a-button type="primary" @click="edit(record)">编辑</a-button>
            <a-popconfirm
                    title="删除后无法恢复，确认删除吗?"
                    ok-text="是"
                    cancel-text="否"
                    @confirm="del(record.id)"

            >
                <a-button type="danger" >删除</a-button>
            </a-popconfirm>
        </template>
    </a-table>
    <a-modal
            v-model:visible="modalVisible"
            title="内容编辑表单"
            :confirm-loading="modalLoading"
            @ok="handleModalOk"
            cancel-text="取消"
            ok-text="确定">
        <a-form
                :model="contentEntity"
                :label-col="{ span: 8 }"
                :wrapper-col="{ span: 16 }"

        >
            <a-form-item label="内容类目ID">
                <a-select v-model:value="contentEntity.categoryId">
                    <a-select-option v-for="item in categoryList" :value="item.id" :key="item.id">
                        {{item.name}}
                    </a-select-option>
                </a-select>
            </a-form-item>

            <a-form-item label="内容标题">
                <a-input v-model:value="contentEntity.title"/>
            </a-form-item>
            <a-form-item label="链接">
                <a-input v-model:value="contentEntity.url"/>
            </a-form-item>
            <a-form-item label="图片">
                <a-upload
                        v-model:file-list="fileList"
                        name="file"
                        list-type="picture-card"
                        class="avatar-uploader"
                        :show-upload-list="true"
                        :action="action"
                        :before-upload="beforeUpload"
                        @change="handleChange"
                >
                    <img v-if="imageUrl" :src="imageUrl" alt="avatar" />
                    <div v-else>
                        <loading-outlined v-if="loading"></loading-outlined>
                        <plus-outlined v-else></plus-outlined>
                        <div class="ant-upload-text">文件上传</div>
                    </div>
                </a-upload>
            </a-form-item>
            <a-form-item label="状态">
                <a-checkbox v-model:value="checked" v-model:checked="checked"/>
            </a-form-item>
            <a-form-item label="排序">
                <a-input v-model:value="contentEntity.sortOrder"/>
            </a-form-item>


        </a-form>

    </a-modal>

</template>

<script lang="ts">
    import { defineComponent,onMounted,ref } from 'vue';
    import axios from "axios";
    import {message, UploadChangeParam} from "ant-design-vue";



    export default defineComponent({
        name: 'BrandsList',
        setup(){

            const contentsList =ref();
            const contents=ref();
            const contentEntity=ref();
            const categoryList=ref();
            const checked=ref(false);

            const columns= [
                {
                    title: '内容ID',
                    dataIndex: 'id',
                    key: 'id',
                    width:20
                },
                {
                    title: '内容类目ID',
                    dataIndex: 'categoryId',
                    key: 'categoryId',
                    width:50
                },
                {
                    title: '内容标题',
                    dataIndex: 'title',
                    key: 'title',
                    width:20
                },
                {
                    title: '链接',
                    dataIndex: 'url',
                    key: 'url',
                    width:20
                },
                {
                    title: '图片',
                    dataIndex: 'pic',
                    key: 'pic',
                    width:20,
                    slots: {customRender: 'pic'}
                },
                {
                    title: '状态',
                    dataIndex: 'status',
                    key: 'status',
                    width:20,
                    slots:{customRender: 'status'}
                },
                {
                    title: '排序',
                    dataIndex: 'sortOrder',
                    key: 'sortOrder',
                    width:20
                },
                {
                    title:'操作',
                    key:'action',
                    slots:{customRender:'action'},
                    width:10
                }
            ];
            const pagination=ref({
                current:1,
                pageSize:5,
                total:0
            });


            const loading=ref<boolean>(false);
            const modalVisible=ref<boolean>(false);
            const modalLoading=ref<boolean>(false);

            const add=()=>{
                modalVisible.value=true;
                checked.value=false;
                fileList.value=[];
                contentEntity.value={};
            }

            const edit=(record:any)=>{
                modalVisible.value=true;
                contentEntity.value=JSON.parse(JSON.stringify(record));
            }

            const del=(id:number)=>{
                console.log(111);
                axios.delete('http://localhost:8899/mall-content/content/delContentById/'+id).then(response=>{
                    if(response.data.code==200){
                        //modalVisible.value=false;
                        //加载最新数据
                        handleQuery({
                            page:pagination.value.current,
                            size:pagination.value.pageSize
                        });
                    }else{
                        message.error(response.data.message);
                    }
                })
            }





            const handleModalOk=()=>{
                modalLoading.value = false;
                contentEntity.value.status=(checked.value?'1':'0');
                axios.post('http://localhost:8899/mall-content/content/addContent',contentEntity.value).then(response=>{
                    modalLoading.value = false;
                    if(response.data.code==200){
                        modalVisible.value=false;
                        //加载最新数据
                        handleQuery({
                            page:pagination.value.current,
                            size:pagination.value.pageSize
                        });
                    }else{
                        message.error(response.data.message);
                    }
                })
            }
            const handleTableChange=(pagination:any)=>{
                handleQuery({
                    page:pagination.current,
                    size:pagination.size
                })
            }
            const handleQuery=(params:any)=>{
                loading.value=true;
                axios.get('http://localhost:8899/mall-content/content/GetAllContent',{
                    params:{
                        page:params.page,
                        size:params.size
                    }
                }).then((response)=>{
                    loading.value=false;
                    contentsList.value=response.data.list;
                    //重置分页按钮
                    pagination.value.current=params.page;
                    pagination.value.total=response.data.total;
                });
            }
            onMounted(()=>{
                handleQuery({
                    page:1,
                    size:pagination.value.pageSize

                });
                QueryCategory();
            })

            //文件上传
            const fileList=ref([]);
            const imageUrl=ref<string>('');
            const action=ref("http://localhost:8899/mall-content/fileUpload/uploadFile");

            const handleChange = (info: UploadChangeParam) => {
                if (info.file.status === 'uploading') {
                    loading.value = true;
                    return;
                }
                if (info.file.status === 'done') {
                    loading.value = false;
                    //console.log("上传文件code：" + info.file.response.message);
                    if (info.file.response.data) {
                        // imageUrl.value = info.file.response.message;
                        //获取回调回来的图片的url，最后保存到mysql
                        contentEntity.value.pic = info.file.response.message;
                    }
                }
                if (info.file.status === 'error') {
                    loading.value = false;
                    message.error('upload error');
                }
            };

            const beforeUpload = (file: File) => {
                const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
                if (!isJpgOrPng) {
                    message.error('You can only upload JPG file!');
                }
                const isLt2M = file.size / 1024 / 1024 < 5;
                if (!isLt2M) {
                    message.error('Image must smaller than 5MB!');
                }
                return isJpgOrPng && isLt2M;
            };

            const QueryCategory=()=>{
                axios.get('http://localhost:8899/mall-content/content/GetContentCategoryList').then(reponse=>{
                    categoryList.value=reponse.data.data;
                })
            }

            return{
                contentsList,
                contentEntity,
                categoryList,
                checked,
                columns,
                handleQuery,
                pagination,
                loading,
                handleTableChange,
                modalVisible,
                modalLoading,
                handleModalOk,
                add,
                edit,
                del,
                fileList,
                imageUrl,
                action,
                handleChange,
                beforeUpload,
                contents
            }

        }

    });
</script>

<style scoped>

</style>